package com.ws.shop.action.admin;

import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.octo.captcha.service.CaptchaService;
import com.ws.shop.bean.Page;
import com.ws.shop.common.JCaptchaEngine;
import com.ws.shop.entity.AdminMenu;
import com.ws.shop.entity.AdminRole;
import com.ws.shop.entity.AdminUser;
import com.ws.shop.service.AdminMenuService;
import com.ws.shop.service.AdminRoleService;
import com.ws.shop.service.AdminUserService;
import com.ws.shop.service.AsynGetTreeMenuService;
import com.ws.shop.util.CommonUtil;
import com.ws.shop.util.RequestUtil;
import com.ws.shop.util.StringUtil;

@Controller
@RequestMapping(value="/admin/*")//请求目录
public class AdminAction extends BaseAdminAction{
	private static Logger log = Logger.getLogger(AdminAction.class);
	@Autowired
	private AdminUserService adminUserService = null;
	@Autowired
	private AdminMenuService adminMenuService;
	@Autowired
	private AsynGetTreeMenuService asynGetTreeMenuService=null;
	@Autowired
	private CaptchaService captchaService;
	@Autowired
	private AdminRoleService adminRoleService;
	
	@RequestMapping(value="login.jhtml",method=RequestMethod.GET)//请求地址
	public String login(){
		return "admin_login";
	}
	
	/**
	 * 用户登录
	 * @return
	 * @throws NoSuchAlgorithmException 
	 */
	@RequestMapping(value="submit.jhtml",method=RequestMethod.POST)
	public String submit(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession(false);
		if(session == null){
			return this.ajaxJsonErrorMessage(response, "会话超时，请重新登陆");
		}
		String captchaID = session.getId();
		String challengeResponse = RequestUtil.getStringParameter(request, JCaptchaEngine.CAPTCHA_INPUT_NAME, null);
		if(challengeResponse == null)
			return this.ajaxJsonErrorMessage(response, "验证码输入有误");
		challengeResponse = challengeResponse.toUpperCase();
		try{
			if (!captchaService.validateResponseForID(captchaID, challengeResponse)) {
				return this.ajaxJsonErrorMessage(response,"验证码输入错误!");
			}
		}catch(Exception e){
			return this.ajaxJsonErrorMessage(response,"验证码输入错误!");
		}
		String username = RequestUtil.getStringParameter(request,"username",null);
		String password = RequestUtil.getStringParameter(request,"password",null);
		String validResult = AdminUser.validUsername(username, false);
		if(validResult != null){
			return this.ajaxJsonErrorMessage(response, validResult);
		}
		validResult = AdminUser.validPassword(password, false);
		if(validResult != null){
			return this.ajaxJsonErrorMessage(response, validResult);
		}
		AdminUser adminUser = adminUserService.findByUsername(username);
		if(adminUser == null){
			log.error("{"+CommonUtil.getIpAddrByRequest(request)+"}{"+username+"}登陆失败：用户名不存在!");
			return this.ajaxJsonErrorMessage(response, "用户不存在");
		}else{
			if(adminUser.getStatus() != 1){
				return this.ajaxJsonErrorMessage(response,"用户被锁定");
			}
			if(!adminUser.getPassword().equals((DigestUtils.md5Hex(password)))){
				return this.ajaxJsonErrorMessage(response, "登陆密码有误");
			}
		}
		Map<String,Object> adminLoginSessionMap = new HashMap<String,Object>();
		adminLoginSessionMap.put(AdminUser.ADMIN_USER_LOGIN_SESSION_KEY, adminUser);
		session.setAttribute(ADMIN_LOGIN_SESSION_KEY, adminLoginSessionMap);
		return this.ajaxJsonSuccessMessage(response, "登陆成功");
	}
	
	@RequestMapping(value="main.jhtml",method=RequestMethod.GET)
	public String main(){
		return "admin_main";
	}
	
	@RequestMapping(value="logout.jhtml",method=RequestMethod.GET)
	public String logout(HttpServletRequest request){
		HttpSession session = request.getSession(false);
		if(session != null)
			session.removeAttribute(ADMIN_LOGIN_SESSION_KEY);
		return "admin_login";
	}
	
	/************************************************
	 * 菜单管理
	 * 
	 ************************************************/
	/**
	 * 菜单列表
	 */
	@RequestMapping(value="adminmenulist.jhtml",method=RequestMethod.GET)
	public String adminmenulist(HttpServletRequest request,Model model){
		List<AdminMenu> adminMenuList = adminMenuService.getAllAdminMenus();
		model.addAttribute("adminMenuList", adminMenuList);
		return "admin_menu_list";
	}
	
	/*
	 * 添加、修改菜单
	 */
	@RequestMapping(value="adminmenuinput.jhtml",method=RequestMethod.GET)
	public String adminmenuinput(HttpServletRequest request,Model model){
		int menuid = RequestUtil.getIntParameter(request,"menuid",0);
		if(menuid > 0){
			AdminMenu adminMenu = adminMenuService.getMenuById(menuid);
			if(adminMenu != null)
				model.addAttribute("adminMenu", adminMenu);
		}
		List<AdminMenu> adminMenuList = adminMenuService.getAllAdminMenus();
		model.addAttribute("adminMenuList", adminMenuList);
		return "admin_menu_input";
	}
	
	@RequestMapping(value="adminmenusave.jhtml",method=RequestMethod.POST)
	public String adminmenusave(HttpServletRequest request,HttpServletResponse response){
		int menuid = RequestUtil.getIntParameter(request,"menuid",0);
		String menuname=RequestUtil.getStringParameter(request,"menuname","");
		String descs=RequestUtil.getStringParameter(request,"descs","");
		int pmenuid = RequestUtil.getIntParameter(request,"pmenuid",0);
		int menutype = RequestUtil.getIntParameter(request,"menutype",0);
		int ord = RequestUtil.getIntParameter(request,"ord",0);
		int status = RequestUtil.getIntParameter(request,"status",0);
		String linkaddr = RequestUtil.getStringParameter(request,"linkaddr","");
		AdminMenu menu = new AdminMenu();
		menu.setMenuid(menuid);
		menu.setMenuname(menuname);
		menu.setDescs(descs);
		menu.setPmenuid(pmenuid);
		menu.setOrd(ord);
		menu.setLinkaddr(linkaddr);
		menu.setMenutype(menutype);
		menu.setStatus(status);
		try{
			adminMenuService.saveOrUpdate(menu);
			//清空缓存的菜单链接
			DHtmlTreeAction.ROLE_MENUS_MAP.clear();
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+menu,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
		
	}
	
	/*
	 * 删除菜单处理
	 */
	@RequestMapping(value="adminmenudel.jhtml",method=RequestMethod.GET)
	public String adminmenudel(HttpServletRequest request,HttpServletResponse response){
		int menuid = RequestUtil.getIntParameter(request,"menuid",0);
		try{
			Object[] result = adminMenuService.delMenu(menuid);
			if(0 != (Integer)result[0]){
				return this.ajaxJsonErrorMessage(response, (String)result[1]);
			}
			//清空缓存的菜单链接
			DHtmlTreeAction.ROLE_MENUS_MAP.clear();
			return this.ajaxJsonErrorMessage(response, "删除成功");
		}catch(Exception e){
			log.error("删除菜单失败:menuid="+menuid,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙， 请稍后再试");
		}
	}
	
	
	/************************************************
	 * 角色管理
	 * 
	 ************************************************/
	/**
	 * 角色列表
	 */
	@RequestMapping(value="adminrolelist.jhtml",method=RequestMethod.GET)
	public String adminrolelist(HttpServletRequest request,Model model){
		List<AdminRole> adminRoleList = adminRoleService.findRoleListAll();
		request.setAttribute("adminRoleList", adminRoleList);
		return "admin_role_list";
	}
	
	/*
	 * 增加角色
	 */
	@RequestMapping(value="adminroleinput.jhtml",method=RequestMethod.GET)
	public String adminroleinput(HttpServletRequest request,Model model){
		int roleid = RequestUtil.getIntParameter(request,"roleid",0);
		if(roleid > 0){
			AdminRole adminRole = adminRoleService.findRoleById(roleid);
			model.addAttribute("adminRole", adminRole);
		}
		List<AdminRole> adminRoleList = adminRoleService.findRoleListAll();
		request.setAttribute("adminRoleList", adminRoleList);
		return "admin_role_input";
	}
	
	/*
	 * 增加角色处理
	 */
	@RequestMapping(value="adminrolesave.jhtml",method=RequestMethod.POST)
	public String adminrolesave(HttpServletRequest request,HttpServletResponse response){
		int roleid = RequestUtil.getIntParameter(request,"roleid",0);
		String name=RequestUtil.getStringParameter(request,"name","");
		String descs=RequestUtil.getStringParameter(request,"descs","");
		int proleid = RequestUtil.getIntParameter(request,"proleid",-1);
		int status = RequestUtil.getIntParameter(request, "status", 0);
		AdminRole role = new AdminRole();
		role.setRoleid(roleid);
		role.setName(name);
		role.setDescs(descs);
		role.setProleid(proleid == roleid?-1:proleid);
		role.setStatus(status);
		try{
			adminRoleService.saveOrUpdate(role);
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+role,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
	}
	
	/*
	 * 删除角色处理
	 */
	@RequestMapping(value="adminroledel.jhtml",method=RequestMethod.GET)
	public String adminroledel(HttpServletRequest request,HttpServletResponse response){
		int id = RequestUtil.getIntParameter(request,"id",0);
		try{
			Object[] result= adminRoleService.deleteRoleById(id);
			if(0 != (Integer)result[0]){
				return this.ajaxJsonErrorMessage(response, (String)result[1]);
			}
			return this.ajaxJsonErrorMessage(response, "删除成功");
		}catch(Exception e){
			log.error("删除角色失败：id"+id,e);
			return this.ajaxJsonErrorMessage(response, "系统繁忙，请稍后再试");
		}
	}
	
	/**
	 * 转到角色授权页面
	 */
	@RequestMapping(value="adminroleperm.jhtml",method=RequestMethod.GET)
	public String adminroleperm(HttpServletRequest request,Model model){
		int roleid = RequestUtil.getIntParameter(request,"roleid",0);
		AdminRole adminRole = adminRoleService.findRoleById(roleid);
		model.addAttribute("adminRole", adminRole);
		return "admin_role_perm";
	}
	
	@RequestMapping(value="saveadminroleperm.jhtml",method=RequestMethod.POST)
	public String saveadminroleperm(HttpServletRequest request,HttpServletResponse response){
		int roleid=RequestUtil.getIntParameter(request, "roleid", -1);
		String menuids=RequestUtil.getStringParameter(request, "menuids", "");
		if(roleid==-1){
			return this.ajaxJsonErrorMessage(response, "请选择要授权的角色");
		}
		if(StringUtil.isEmpty(menuids)){
			return this.ajaxJsonErrorMessage(response, "您未对该角色设置任何菜单权限");
		}
		int arr[]=StringUtil.string2IntArray(menuids, ",");
		try{
			adminRoleService.saveAdminRolePerm(roleid,arr);
			//重新加载角色菜单
			Map<Integer,AdminMenu> map = asynGetTreeMenuService.getTreemenuByRoleid(roleid);
			DHtmlTreeAction.ROLE_MENUS_MAP.put(roleid, map);
			return this.ajaxJsonSuccessMessage(response, "授权成功");
		}catch(Exception e){
			log.error("操作失败roleid="+roleid+";menuids="+menuids,e);
			return this.ajaxJsonErrorMessage(response, "系统异常，请稍后再试");
		}
	}
	
	/**
	 * 用户列表
	 */
	@RequestMapping(value="adminuserlist.jhtml",method=RequestMethod.GET)
	public String adminuserlist(HttpServletRequest request,Model model){
		int pageno = RequestUtil.getIntParameter(request,Page.PAGE_NO,1);
		String q_username=RequestUtil.getStringParameter(request,"q_username","");
		int status =  RequestUtil.getIntParameter(request,"q_status",-1);
		Page page = adminUserService.getAdminUserListByPage(pageno,20, q_username,status);
		model.addAttribute(Page.PAGE, page);
		model.addAttribute("statusDescs", AdminUser.STATUS_DESCS);
		model.addAttribute("q_username", q_username);
		return "admin_user_list";
	}
	
	/*
	 * 添加、编辑用户
	 */
	@RequestMapping(value="adminuserinput.jhtml",method=RequestMethod.GET)
	public String adminuserinput(HttpServletRequest request,Model model){
		int userid = RequestUtil.getIntParameter(request,"userid",0);
		if(userid > 0){
			AdminUser adminUser = adminUserService.findAdminUserById(userid);
			if(adminUser != null)
				model.addAttribute("adminUser", adminUser);
		}
		List<AdminRole> adminRoleList = adminRoleService.findRoleListAll();
		model.addAttribute("adminRoleList", adminRoleList);
		return "admin_user_input";
	}
	
	@RequestMapping(value="adminusersave.jhtml",method=RequestMethod.POST)
	public String adminusersave(HttpServletRequest request,HttpServletResponse response){
		int userid = RequestUtil.getIntParameter(request,"userid",0);
		String realname=RequestUtil.getStringParameter(request,"realname","");
		String username=RequestUtil.getStringParameter(request,"username","");
		String password = RequestUtil.getStringParameter(request,"password",null);
		String descs=RequestUtil.getStringParameter(request,"descs","");
		int status = RequestUtil.getIntParameter(request,"status",0);
		int roleid = RequestUtil.getIntParameter(request,"roleid",0);
		AdminUser adminUser = new AdminUser();
		adminUser.setUserid(userid);
		adminUser.setRealname(realname);
		adminUser.setUsername(username);
		adminUser.setPassword(password == null?null:DigestUtils.md5Hex(password));
		adminUser.setDescs(descs);
		adminUser.setRoleid(roleid);
		adminUser.setStatus(status);
		adminUser.setCreatid(getLoginAdmin(request.getSession(false)).getUserid());
		try{
			adminUserService.saveOrUpdate(adminUser);
			return this.ajaxJsonSuccessMessage(response, "操作成功");
		}catch(Exception e){
			log.error("操作失败："+adminUser,e);
			return this.ajaxJsonErrorMessage(response, "操作失败");
		}
	}
	
	/*
	 * 删除用户处理
	 */
	@RequestMapping(value="adminuserdel.jhtml",method=RequestMethod.POST)
	public String adminuserdel(HttpServletRequest request,HttpServletResponse response){
		int userid = RequestUtil.getIntParameter(request,"userid",0);
		try{
			Object[] result = adminUserService.deleteAdminUserById(userid);
			if(0 != (Integer)result[0]){
				return this.ajaxJsonErrorMessage(response, (String)result[1]);
			}
			return this.ajaxJsonSuccessMessage(response, "删除成功");
		}catch(Exception e){
			log.error("删除用户失败userid="+userid,e);
			return this.ajaxJsonErrorMessage(response, "删除失败");
		}
		
	}
	
	/**
	 * 修改密码
	 */
	@RequestMapping(value="adminuserpasswdedit.jhtml",method=RequestMethod.GET)
	public String adminuserpasswdedit(){
		return "admin_user_passwd_edit";
	}
	
	/**
	 * 修改密码处理
	 */
	@RequestMapping(value="adminuserpasseditdo.jhtml",method=RequestMethod.POST)
	public String adminuserpasseditdo(HttpServletRequest request,HttpServletResponse response){
		HttpSession session = request.getSession(false);
		AdminUser adminUser = getLoginAdmin(session);
		String oldpassword = RequestUtil.getStringParameter(request,"oldpassword",null);
		String password = RequestUtil.getStringParameter(request,"password",null);
		if(!adminUser.getPassword().equals(DigestUtils.md5Hex(oldpassword))){
			return this.ajaxJsonErrorMessage(response, "旧密码错误");
		}
		try{
			String newpw = DigestUtils.md5Hex(password);
			adminUserService.updateAdminUserPassword(adminUser.getUserid(),newpw);
			adminUser.setPassword(newpw);
			return this.ajaxJsonSuccessMessage(response, "更新密码成功");
		}catch(Exception e){
			log.error("更新密码失败userid="+adminUser.getUserid(),e);
			return this.ajaxJsonErrorMessage(response, "更新密码失败");
		}
	}
	
	// 后台中间(显示/隐藏菜单)
	@RequestMapping(value="top.jhtml",method=RequestMethod.GET)
	public String top(HttpServletRequest request,Model model) {
		AdminUser adminUser = getLoginAdmin(request.getSession(false));
		model.addAttribute("adminUser", adminUser);
		return "admin_top";
	}
	
	@RequestMapping(value="down.jhtml",method=RequestMethod.GET)
	public String down(){
		return "admin_down";
	}
	
	@RequestMapping(value="index.jhtml",method=RequestMethod.GET)
	public String index(HttpServletRequest request,Model model){
		model.addAttribute("treeUrl",RequestUtil.getStringParameter(request,"q",""));
		return "admin_desktop";
	}
	
	@RequestMapping(value="desktop.jhtml",method=RequestMethod.GET)
	public String desktop(HttpServletRequest request,Model model){
		model.addAttribute("treeUrl",RequestUtil.getStringParameter(request,"q",""));
		return "admin_desktop";
	}
	
	@RequestMapping(value="left.jhtml",method=RequestMethod.GET)
	public String left(HttpServletRequest request,Model model){
		AdminUser adminUser = getLoginAdmin(request.getSession(false));
		if(adminUser == null)
			return ERROR;
		Map<Integer,AdminMenu> map = DHtmlTreeAction.ROLE_MENUS_MAP.get(adminUser.getRoleid());
		if(map == null){
			map = asynGetTreeMenuService.getTreemenuByRoleid(adminUser.getRoleid());
			DHtmlTreeAction.ROLE_MENUS_MAP.put(adminUser.getRoleid(), map);
		}
		StringBuilder result=new StringBuilder("[");
		Collection<AdminMenu> coll = map.values();
		AdminMenu menu = null;
		for(Iterator<AdminMenu> it = coll.iterator();it.hasNext();){
			menu=it.next();
			if(!StringUtil.isEmpty(menu.getLinkaddr())){
				result.append(menu.getMenuid()+",'"+menu.getLinkaddr()+"',");
			}	
		}
		result.append("0]");
		model.addAttribute("allMenuLinkAddr", result.toString());
		return "admin_left";
	}
	
	@RequestMapping(value="center.jhtml",method=RequestMethod.GET)
	public String center(){
		return "admin_center";
	}
	
}
